重载运算符(operator)

您所在的位置:网站首页 dart operator重载运算符 重载运算符(operator)

重载运算符(operator)

2024-07-16 20:09| 来源: 网络整理| 查看: 265

什么是运算符重载

重载我们分析过了,就是对一个已有的函数,使其参数的个数,类型不同来赋予新的含义,实现新的功能。那么运算符也可以被重载赋予新的含义和功能。这就运算符重载。

为什么会用运算符重载机制

我们在开发中都使用过运算符,一般情况下我们接触最多的就是加减乘除,还有new,delete这些运算法,直接使用他们只能对单一类型的数据进行操作。例如我们想对自定义类型进行运算操作时,该怎么办呢?重载运算符就显得极其重要了。

#pragma warning(disable : 4996) #include using namespace std; class Complex { friend Complex Add(Complex &c1, Complex &c2); friend Complex operator+(Complex &c1, Complex &c2); public: Complex(int a, int b) { this->m_a = a; this->m_b = b; } //成员函数(在类的内部完成两个数据的和) int GetAdd() { return m_a + m_b; } //成员函数(在类的内部完成两个类的数据的和) Complex GetAdd(Complex &c1) { Complex temp = Complex(this->m_a + c1.m_a, this->m_b + c1.m_b); return temp; } private: int m_a, m_b; }; //全局函数(要访问类的私有成员可以使用友元friend) Complex Add(Complex &c1,Complex &c2) { Complex temp = Complex(c1.m_a + c2.m_a, c1.m_b + c2.m_b); return temp; } //重载“+”运算法 Complex operator+(Complex &c1, Complex &c2) { Complex temp = Complex(c1.m_a + c2.m_a, c1.m_b + c2.m_b); return temp; } int main() { //使用成员函数 Complex c1(1, 2), c2(3, 4); int a1 = c1.GetAdd(); int a2 = c2.GetAdd(); int a3 = a1 + a2; cout m_len = obj.m_len; this->str = new char[m_len + 1]; strcpy(str, obj.str); } void MyString::MyPrint() { cout m_len = 0; } MyString & MyString::operator=(const MyString &obj) { if (this->str != NULL) { delete[] str; m_len = 0; } this->m_len = obj.m_len; this->str = new char[m_len+1]; strcpy(str, obj.str); return *this; } MyString& MyString::operator=( const char *s) { if (this->str != NULL) { delete[] str; m_len = 0; } if (s == NULL) { m_len = 0; str = new char[m_len + 1]; strcpy(str, ""); } else { m_len = strlen(s); str = new char[m_len + 1]; strcpy(str, s); } return *this; } char & MyString::operator[](int index) const { return str[index]; } bool MyString::operator==(const char * str)const { if (str == NULL) { if (this->m_len == 0) return true; else return false; } else { if (this->m_len == strlen(str)) { return !strcmp(this->str, str); } else { return false; } } } bool MyString::operator!=(const char * str)const { return !(*this == str); } bool MyString::operator==(const MyString & s)const { if (m_len != s.m_len) return false; else { return !strcmp(this->str, s.str); } } bool MyString::operator!=(const MyString & s)const { return !(*this == s); } char * MyString::Str() { return this->str; } const char * MyString::c_Str() { return this->str; } int MyString::Length() { return this->m_len; } //bool MyString::operatorstr, str ); //} // //bool MyString::operator>(const char * str) const //{ // return strcmp(str, this->str); //} // //bool MyString::operatorstr, s.str); //} // //bool MyString::operator>(const MyString & s) const //{ // return strcmp(s.str, this->str); //} ostream & operator> s.str; } 总结

1、对于自定义类型进行运算时,我们会使用到运算符重载

2、成员函数和友元函数都可以重载运算符,其参数,代码实现,应用场景不同

3、运算符的重载符合运算符的优先级,结合性,操作数。

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3